package cn.alpha.intell.rbtlib.manager.media;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;

import java.io.IOException;

/**
 * @author jinlongfeng
 * @version 2.0.9
 * @desc 该类用于播放 mp3 音频文件，并且回调 播放完成和出现异常
 */
public  class AudioMediaPlay {

    private static final String TAG = "AudioMediaPlay";

      public   interface  AudioMediaPlayCallBcak {
            void   onfinished();
            void   onfailed();
        }

        private MediaPlayer mMediaPlayer ;
        public void setAudioMediaPlayCallBcak(AudioMediaPlayCallBcak audioMediaPlayCallBcak) {
            mAudioMediaPlayCallBcak = audioMediaPlayCallBcak;
        }

        private AudioMediaPlayCallBcak mAudioMediaPlayCallBcak;


        public AudioMediaPlay(Context context, int resid){

            mMediaPlayer = MediaPlayer.create(context,resid);
            initMediaPlayer();

        }

        public AudioMediaPlay(Context context,Uri resid){

            mMediaPlayer = MediaPlayer.create(context,resid);
            initMediaPlayer();

        }

        private void initMediaPlayer() {

           /* try{
                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                    mMediaPlayer.stop();
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (mMediaPlayer != null) {
                        mMediaPlayer.release();
                        mMediaPlayer = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/

            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {

                    if (mAudioMediaPlayCallBcak!=null){
                        mAudioMediaPlayCallBcak.onfailed();
                    }
                    Log.d(TAG,"onError");

                    stopPlayer();
                    return true;
                }
            });
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (mAudioMediaPlayCallBcak!=null){
                        mAudioMediaPlayCallBcak.onfinished();
                    }
                    stopPlayer();
                }
            });
        }

        public void startPlay(){
            mMediaPlayer.start();
        }
        
        private void stopPlayer(){
            mMediaPlayer.stop();//停止播放  
            mMediaPlayer.release();//释放资源  
            mMediaPlayer=null;
        }

    }
